package com.example.xiaoshuo_yudu.listener;
import com.example.xiaoshuo_yudu.entity.Message.ChapterPreCacheMessage;
import com.example.xiaoshuo_yudu.mapper.ChapterTablesMapper;
import com.example.xiaoshuo_yudu.utils.Const;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Component
public class ChapterPreCacheConsumer {
    private static final Logger log = LoggerFactory.getLogger(ChapterPreCacheConsumer.class);
    
    @Autowired
    private ChapterTablesMapper chapterTablesMapper;
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 监听章节预缓存队列，异步处理缓存
     */
    @RabbitListener(queues = "chapter_pre_cache")
    public void handleChapterPreCache(ChapterPreCacheMessage message) {
        try {
            Integer bookId = message.getBookId();
            Integer chapterId = message.getChapterId();
            String tableName = message.getTableName();
            
            // 构建缓存键
            String cacheKey = Const.SUB_CHAPTER_DATA + ":" + bookId + ":" + chapterId;
            // 已缓存则直接返回
            if (redisTemplate.hasKey(cacheKey)) {
                return;
            }
            // 查询章节数据
            Map<String, Object> chapterDetail = chapterTablesMapper.getChapterDetail(tableName, bookId, chapterId);
            if (chapterDetail != null && !chapterDetail.isEmpty()) {
                // 处理章节数据格式
                chapterDetail.put("id", chapterId);
                chapterDetail.put("bookId", bookId);
                chapterDetail.put("title", chapterDetail.get("chapter_title"));
                chapterDetail.remove("chapter_title");
                chapterDetail.put("chapterContent", chapterDetail.get("chapter_content"));
                chapterDetail.remove("chapter_content");
                
                // 存入缓存，设置5分钟过期（比当前章节短，减少空间占用）
                redisTemplate.opsForValue().set(cacheKey, chapterDetail, 5, TimeUnit.MINUTES);
            } else {
                // 缓存空结果，1分钟过期
                redisTemplate.opsForValue().set(cacheKey, null, 1, TimeUnit.MINUTES);
            }
        } catch (Exception e) {
            log.error("预缓存处理失败", e);
        }
    }
}
    